package com.spzx.common.rabbit.service;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送消息
     *
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param message    消息
     */
    public boolean sendMessage(String exchange, String routingKey, Object message) {
        //重新发送数据 携带数据
        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        guiguCorrelationData.setMessage(message);
        guiguCorrelationData.setExchange(exchange);
        guiguCorrelationData.setRoutingKey(routingKey);
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(guiguCorrelationData),10, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend(exchange, routingKey, message,guiguCorrelationData);
        return true;
    }

    /**
     * 发送延迟消息
     * @param exchange_delay 交换机
     * @param routing_delay 路由键
     * @param msg 消息
     * @param delayTime 时间
     */
    public void sendDelayMessage(String exchangeDelay, String routingDelay, Object msg, int delayTime) {
        //重发消息
        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        String uuid=UUID.randomUUID().toString().replaceAll("-","");
        guiguCorrelationData.setId(uuid);
        guiguCorrelationData.setMessage(msg);
        guiguCorrelationData.setExchange(exchangeDelay);
        guiguCorrelationData.setRoutingKey(routingDelay);
        guiguCorrelationData.setDelay(true);//延迟消息
        guiguCorrelationData.setDelayTime(delayTime);//秒
        redisTemplate.opsForValue().set(uuid,JSON.toJSONString(guiguCorrelationData),10,TimeUnit.MINUTES);
        //处理器指定消息延迟时间
        MessagePostProcessor messagePostProcessor=(message)->{
            message.getMessageProperties().setDelay(delayTime*1000);//毫秒
            return message;
        };
        rabbitTemplate.convertAndSend(exchangeDelay,routingDelay,msg,messagePostProcessor,guiguCorrelationData);
    }


}